<?php
use Workerman\Worker;
use \Workerman\Connection\AsyncTcpConnection;
$worker = new Worker("http://0.0.0.0:3333");
$worker->count = 2;
$worker->name = 'httpServ';
$worker->onWorkerStart = function() {
    global $mysql,$task_connection;
    $task_connection = new AsyncTcpConnection('Text://127.0.0.1:12345');
};
$worker->onMessage = function($connection, $data)
{
    //var_dump($_GET, $_POST, $_COOKIE, $_SESSION, $_SERVER, $_FILES);
    //print_r($_GET);
    if(isset($_GET['ttt'])){
        $connection->send("ttt");
        return;
    }  
    //if($_GET['send_mail']) send_mail();

    // 与远程task服务建立异步连接，ip为远程task服务的ip，如果是本机就是127.0.0.1，如果是集群就是lvs的ip
    global $task_connection;
    $task_data = array(
        'function' => 'send_mail',
        'args'     => array('from'=>'xxx', 'to'=>'xxx', 'contents'=>'xxx'),
    );
    // 发送数据
    $task_connection->send(json_encode($task_data));
    $task_connection->onMessage = function($task_connection, $task_result)use($connection)
    {
        var_dump($task_result);
        $task_connection->close();
        $connection->send('task complete');
    };
    $task_connection->connect();
    $connection->send("1 \n");
};

if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}

function ttt(){
    sleep(5);
    echo 'ttt';
}

function send_mail(){
    $socket = stream_socket_client("tcp://127.0.0.1:12345", $errno, $errmsg, 5);
    if(!$socket) echo $errmsg;
    $mail_data = array("from"=>"...", "to"=>"...", "content"=>"...");
    // 注意，Text协议后面"\n"换行符是必须的
    $mail_buffer = json_encode($mail_data)."\n";
    $rs = fwrite($socket, $mail_buffer);
    print_r($rs);
}
